package com.wn32.main.demo18;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DbUtils {
    private static String driver = "";
    private static String url = "";
    private static String user = "";
    private static String pass = "";

    static {
        Properties p = new Properties();
        try {
            p.load(DbUtils.class.getClassLoader().getResourceAsStream("moon.properties"));
            driver = p.getProperty("driver");
            url = p.getProperty("url");
            user = p.getProperty("user");
            pass = p.getProperty("pass");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //查询
    public static <T> List<T> query(String sql, Class<T> clazz) {
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, user, pass);
            PreparedStatement st = conn.prepareStatement(sql);
            ResultSet rs = st.executeQuery();
            ResultSetMetaData meta = rs.getMetaData();
            List<T> list = new ArrayList<T>();
            while (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 1; i <= meta.getColumnCount(); i++) {
                    String colname = meta.getColumnName(i);
                    String coltype = meta.getColumnTypeName(i);
                    Field f = clazz.getDeclaredField(colname);
                    f.setAccessible(true);
                    if (coltype.toLowerCase().contains("int")) {
                        f.set(t, rs.getInt(colname));
                    } else if (coltype.toLowerCase().contains("varchar")) {
                        f.set(t, rs.getString(colname));
                    } else if (coltype.toLowerCase().contains("date")) {
                        f.set(t, rs.getDate(colname));
                    } else {

                    }
                }
                list.add(t);
            }
            conn.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //queryOne

    //exec
    public static void exec(String sql){
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, user, pass);
            PreparedStatement st = conn.prepareStatement(sql);
            st.execute(sql);
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //
}
